package com.code;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 描述:
 * 文件copy
 * @author luzhongfu
 * Created by lucky on 2020-05-22 11:02 AM
 */
public class FileCopy {

    public static void fileCopy(String source, String target){
        try(InputStream fileInputStream = new FileInputStream(source)){
            try(OutputStream fileOutputStream = new FileOutputStream(target)){
                byte[] bytes = new byte[4069];
                int read = 0;
                while ((read = fileInputStream.read(bytes)) != -1){
                    fileOutputStream.write(bytes,0,read);
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void fileCopyNio(String source, String target){
        try(FileInputStream fileInputStream = new FileInputStream(source)){
            try(OutputStream fileOutputStream = new FileOutputStream(target)){
                FileChannel channel =  fileInputStream.getChannel();
                FileChannel outChannel = ((FileOutputStream) fileOutputStream).getChannel();

                ByteBuffer allocate = ByteBuffer.allocate(4096);
                while (channel.read(allocate) != -1){
                    //设置游标
                    allocate.flip();
                    outChannel.write(allocate);
                    //清除游标
                    allocate.clear();
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        fileCopyNio("/Users/luzhongfu/Documents/BA874453-6ECE-44a1-9537-A0C61AF542D9.txt","/Users/luzhongfu/Documents/bcd.txt");
    }
}
